<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function themeConfig($form) {
    // Logo设置
    $logoUrl = new Typecho_Widget_Helper_Form_Element_Text('logoUrl', NULL, NULL, 
        _t('站点 LOGO 地址'), 
        _t('在这里填入一个图片 URL 地址, 以在网站标题前加上一个 LOGO'));
    $form->addInput($logoUrl);
    
    // 主题配色
    $primaryColor = new Typecho_Widget_Helper_Form_Element_Text('primaryColor', NULL, '#4e54c8', 
        _t('主题主色调'), 
        _t('默认为#4e54c8，可自定义修改'));
    $form->addInput($primaryColor);
    
    // 社交链接
    $socialLinks = new Typecho_Widget_Helper_Form_Element_Textarea('socialLinks', NULL, NULL,
        _t('社交链接'), 
        _t('按照格式填写社交链接，一行一个，格式：图标名|链接|标题，例如：github|https://github.com/xxx|我的GitHub'));
    $form->addInput($socialLinks);
    
    // 侧边栏设置
    $sidebarBlock = new Typecho_Widget_Helper_Form_Element_Checkbox('sidebarBlock', 
        array(
            'ShowRecentPosts'     => _t('显示最新文章'),
            'ShowRecentComments'  => _t('显示最近回复'),
            'ShowCategory'        => _t('显示分类'),
            'ShowArchive'         => _t('显示归档'),
            'ShowOther'           => _t('显示其它杂项')
        ),
        array('ShowRecentPosts', 'ShowRecentComments', 'ShowCategory', 'ShowArchive', 'ShowOther'), 
        _t('侧边栏显示')
    );
    $form->addInput($sidebarBlock->multiMode());
    
    // 代码高亮主题
    $codeTheme = new Typecho_Widget_Helper_Form_Element_Select('codeTheme',
        array(
            'github'    => _t('GitHub'),
            'monokai'   => _t('Monokai'),
            'dracula'   => _t('Dracula'),
            'tomorrow'  => _t('Tomorrow')
        ),
        'github',
        _t('代码高亮主题'),
        _t('选择一个代码高亮主题')
    );
    $form->addInput($codeTheme);
    
    // 文章页面设置
    $postShowTOC = new Typecho_Widget_Helper_Form_Element_Radio('postShowTOC',
        array(
            '0' => _t('不显示'),
            '1' => _t('显示')
        ),
        '1',
        _t('文章目录显示'),
        _t('是否显示文章目录')
    );
    $form->addInput($postShowTOC);

    // 公告栏设置
    $noticeSwitch = new Typecho_Widget_Helper_Form_Element_Radio(
        'noticeSwitch',
        array(
            '1' => _t('开启'),
            '0' => _t('关闭')
        ),
        '0',
        _t('是否开启公告栏'),
        _t('开启后会在首页文章列表上方显示公告信息')
    );
    $form->addInput($noticeSwitch);

    $noticeContent = new Typecho_Widget_Helper_Form_Element_Textarea(
        'noticeContent',
        null,
        null,
        _t('公告内容'),
        _t('支持HTML标签，请注意标签闭合')
    );
    $form->addInput($noticeContent);

    $noticeColor = new Typecho_Widget_Helper_Form_Element_Text(
        'noticeColor',
        null,
        '#4e54c8',
        _t('公告栏主题色'),
        _t('支持CSS颜色值，默认为#4e54c8')
    );
    $form->addInput($noticeColor);

    // 导航卡片设置
    $navSwitch = new Typecho_Widget_Helper_Form_Element_Radio(
        'navSwitch',
        array(
            '1' => _t('开启'),
            '0' => _t('关闭')
        ),
        '0',
        _t('是否开启导航卡片'),
        _t('开启后会在首页公告栏下方显示导航卡片')
    );
    $form->addInput($navSwitch);

    $defaultNavCards = <<<JSON
[
    {
        "title": "GitHub",
        "desc": "开源代码托管平台",
        "link": "https://github.com",
        "icon": "fab fa-github"
    },
    {
        "title": "文档中心",
        "desc": "查看主题使用文档",
        "link": "https://docs.example.com",
        "icon": "fas fa-book"
    }
]
JSON;

    $navCards = new Typecho_Widget_Helper_Form_Element_Textarea(
        'navCards',
        null,
        $defaultNavCards,
        _t('导航卡片配置'),
        _t('请按JSON格式配置，包含title(标题)、desc(描述)、link(链接)、icon(图标class)字段。支持 Font Awesome 图标')
    );
    $form->addInput($navCards);

    // 添加自定义样式
    echo '<style>
        .notice-settings, .nav-settings {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 10px 0;
            transition: all 0.3s ease;
        }
        .hidden {
            display: none;
        }
        .typecho-option {
            padding: 20px !important;
        }
    </style>';

    // 添加JavaScript控制显示/隐藏
    echo '<script>
        window.addEventListener("load", function() {
            // 获取设置组
            const noticeSwitch = document.querySelector("[name=\'noticeSwitch\']");
            const noticeSettings = document.querySelectorAll("[name=\'noticeContent\'], [name=\'noticeColor\']")
                .map(el => el.closest(".typecho-option"));
            
            const navSwitch = document.querySelector("[name=\'navSwitch\']");
            const navSettings = document.querySelectorAll("[name=\'navCards\']")
                .map(el => el.closest(".typecho-option"));
            
            // 包装设置组
            const wrapSettings = (elements, className) => {
                const wrapper = document.createElement("div");
                wrapper.className = className;
                elements[0].parentNode.insertBefore(wrapper, elements[0]);
                elements.forEach(el => wrapper.appendChild(el));
                return wrapper;
            };
            
            // 创建设置组包装
            const noticeWrapper = wrapSettings(noticeSettings, "notice-settings");
            const navWrapper = wrapSettings(navSettings, "nav-settings");
            
            // 初始化显示状态
            const updateVisibility = (wrapper, value) => {
                if (value === "1") {
                    wrapper.classList.remove("hidden");
                } else {
                    wrapper.classList.add("hidden");
                }
            };
            
            // 设置初始状态
            updateVisibility(noticeWrapper, noticeSwitch.value);
            updateVisibility(navWrapper, navSwitch.value);
            
            // 监听开关变化
            noticeSwitch.addEventListener("change", (e) => {
                updateVisibility(noticeWrapper, e.target.value);
            });
            
            navSwitch.addEventListener("change", (e) => {
                updateVisibility(navWrapper, e.target.value);
            });
        });
    </script>';
}

// 文章阅读次数统计
function get_post_view($archive) {
    $cid = $archive->cid;
    $db = Typecho_Db::get();
    $prefix = $db->getPrefix();
    
    // 从数据库中获取阅读量
    if (!array_key_exists('views', $db->fetchRow($db->select()->from('table.contents')))) {
        // 如果数据表不存在 views 字段，则创��它
        $db->query('ALTER TABLE `' . $prefix . 'contents` ADD `views` INT(10) DEFAULT 0;');
    }
    
    // 获取阅读量
    $row = $db->fetchRow($db->select('views')->from('table.contents')->where('cid = ?', $cid));
    $views = Typecho_Cookie::get('extend_contents_views_'.$cid);
    
    if(empty($views)){
        // 如果访客第一次查看，则增加阅读量
        $views = $row['views'];
        $db->query($db->update('table.contents')
            ->rows(array('views' => (int)$views+1))
            ->where('cid = ?', $cid));
        $views = (int)$views+1;
        Typecho_Cookie::set('extend_contents_views_'.$cid, $views); //设置Cookie
    }
    
    echo $views;
}

// 文章阅读量排行
function get_most_viewed($limit = 10) {
    $db = Typecho_Db::get();
    $result = $db->fetchAll($db->select()->from('table.contents')
        ->where('status = ?','publish')
        ->where('type = ?', 'post')
        ->where('created <= ?', time())
        ->order('views', Typecho_Db::SORT_DESC)
        ->limit($limit)
    );
    
    if($result) {
        foreach($result as $val) {
            $val = Typecho_Widget::widget('Widget_Abstract_Contents')->push($val);
            $post_title = htmlspecialchars($val['title']);
            $permalink = $val['permalink'];
            $views = $val['views'];
            
            echo "<li><a href=\"$permalink\" title=\"$post_title\">$post_title</a> ($views 次阅读)</li>";
        }
    }
}

// 自动生成文章目录
function generate_post_toc($content) {
    global $toc_count;
    global $toc;

    $toc = array();
    $toc_count = 0;

    $content = preg_replace_callback('/<h([1-6])(.*?)>(.*?)<\/h\1>/i', function($matches) {
        global $toc_count;
        global $toc;

        $toc_count++;
        $title = strip_tags($matches[3]);
        $level = $matches[1];
        $id = 'toc-'.$toc_count;

        $toc[] = array(
            'text' => $title,
            'level' => $level,
            'id' => $id
        );

        return '<h'.$level.$matches[2].' id="'.$id.'">'.$matches[3].'</h'.$level.'>';
    }, $content);

    return $content;
}

// 输出文章目录
function output_post_toc() {
    global $toc;
    if (empty($toc)) return '';

    $output = '<div class="post-toc"><h3>文章目录</h3><ul>';
    foreach ($toc as $item) {
        $output .= '<li class="toc-level-'.$item['level'].'"><a href="#'.$item['id'].'">'.$item['text'].'</a></li>';
    }
    $output .= '</ul></div>';

    return $output;
}

// 添加自定义字段
function themeFields($layout) {
    $banner = new Typecho_Widget_Helper_Form_Element_Text('banner', NULL, NULL,
        _t('文章头图'),
        _t('输入文章头图链接'));
    $layout->addItem($banner);
    
    $summary = new Typecho_Widget_Helper_Form_Element_Textarea('summary', NULL, NULL,
        _t('文章摘要'),
        _t('输入文章摘要，如果不输入将自动截取文章前150个字'));
    $layout->addItem($summary);
}

// 主题初始化
function themeInit($archive) {
    // 添加代码高亮支持
    if ($archive->is('single')) {
        $codeTheme = Helper::options()->codeTheme;
        Typecho_Widget::widget('Widget_Options')->to($options);
        if ($codeTheme) {
            echo '<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.5.0/build/styles/'.$codeTheme.'.min.css">';
            echo '<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.5.0/build/highlight.min.js"></script>';
            echo '<script>hljs.initHighlightingOnLoad();</script>';
        }
    }
}

